package com.example.mr5.money.main.myincome.addincome;

import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mr5.money.R;
import com.example.mr5.money.constant.Constant;
import com.example.mr5.money.model.CommonType;
import com.example.mr5.money.util.DatabaseHelper;
import com.example.mr5.money.util.DateUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class AddMyIncomeActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    private ListView firstList;
    private ListView secondList;
    private FirstListAdapter firstListAdapter;
    private SecondListAdapter secondListAdapter;
    private List<CommonType> commonTypeList;
    private List<CommonType> commonTypeChildList;
    private Calendar now;
    private AlertDialog dialog;
    private Window window;
    private TextView dateText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_my_income);
        initData();
        initView();
    }

    private void initData() {
        CommonType commonType1;
        CommonType commonType2;
        commonTypeList = new ArrayList<>();

        DatabaseHelper databaseHelper = DatabaseHelper.getDBInstance(this);
        SQLiteDatabase db = databaseHelper.getReadableDatabase();

        Cursor cursor1 = db.query(Constant.DATABASE_INCOME_FIRST_TABLE_NAME, null, null, null, null, null, null, null);
        while (cursor1.moveToNext()) {
            commonType1 = new CommonType();
            commonTypeChildList = new ArrayList<>();
            String firstTitle = cursor1.getString(cursor1.getColumnIndex(Constant.DATABASE_INCOME_FIRST_TABLE_FIELD_TITLE));
            commonType1.setName(firstTitle);
            Cursor cursor2 = db.query(Constant.DATABASE_INCOME_SECOND_TABLE_NAME, null,
                    Constant.DATABASE_INCOME_SECOND_TABLE_FIELD_FIRST_TITLE + "= ?", new String[]{commonType1.getName()}, null, null, null);
            while (cursor2.moveToNext()) {
                commonType2 = new CommonType();
                String secondTitle = cursor2.getString(cursor2.getColumnIndex(Constant.DATABASE_INCOME_SECOND_TABLE_FIELD_TITLE));
                String parentTitle = cursor2.getString(cursor2.getColumnIndex(Constant.DATABASE_INCOME_SECOND_TABLE_FIELD_FIRST_TITLE));
                commonType2.setName(secondTitle);
                commonType2.setParentName(parentTitle);
                commonTypeChildList.add(commonType2);
            }
            cursor2.close();
            commonType1.setChildrenList(commonTypeChildList);
            commonTypeList.add(commonType1);
        }
        cursor1.close();
        commonTypeChildList = new ArrayList<>();
        if (commonTypeList.size()>0 && commonTypeList.get(0).getChildrenList() != null) {
            commonTypeChildList.addAll(commonTypeList.get(0).getChildrenList());
        }
        firstListAdapter = new FirstListAdapter(this, commonTypeList);
        secondListAdapter = new SecondListAdapter(this, commonTypeChildList);
    }

    private void initView() {

        setTitle(getResources().getString(R.string.activity_name_add_income));
        android.support.v7.app.ActionBar bar = getSupportActionBar();
        bar.setDisplayHomeAsUpEnabled(true);

        firstList = (ListView) findViewById(R.id.income_first_list);
        secondList = (ListView) findViewById(R.id.income_second_list);
        firstList.setAdapter(firstListAdapter);
        firstList.setOnItemClickListener(this);
        secondList.setAdapter(secondListAdapter);
        secondList.setOnItemClickListener(this);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent.getId() == R.id.income_first_list) {
            commonTypeChildList.clear();
            commonTypeChildList.addAll(commonTypeList.get(position).getChildrenList());
            secondListAdapter.notifyDataSetChanged();
            firstListAdapter.setSelection(position);
            firstListAdapter.notifyDataSetChanged();

        } else if (parent.getId() == R.id.income_second_list) {
//            Toast.makeText(AddMyIncomeActivity.this, position + "", Toast.LENGTH_LONG).show();
            showDialog(commonTypeChildList.get(position));
        }
    }

    private void showDialog(final CommonType commonType) {
        dialog = new AlertDialog.Builder(this).create();
        dialog.setView(new EditText(this));
        dialog.show();
        window = dialog.getWindow();
        window.setContentView(R.layout.dialog_add_record);
        final TextView dialogTitle = (TextView) window.findViewById(R.id.add_dialog_title);
        dialogTitle.setText("新增收入");
        final TextView dialogFrom = (TextView) window.findViewById(R.id.add_dialog_frome);
        dialogFrom.setText("收入来源:");
        final TextView incomeFrom = (TextView) window.findViewById(R.id.record_from);
        incomeFrom.setText(commonType.getParentName() + "-" + commonType.getName());
        final EditText howMuch = (EditText) window.findViewById(R.id.how_much);
        final Button confirm = (Button) window.findViewById(R.id.confirm);
        final Button cancel = (Button) window.findViewById(R.id.cancel);
        dateText = (TextView) window.findViewById(R.id.text_date);
        final ImageView dataImg = (ImageView) window.findViewById(R.id.img_date);
        now = Calendar.getInstance();
        dateText.setText(now.get(Calendar.YEAR) + "-" + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.DAY_OF_MONTH));

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatabaseHelper helper = DatabaseHelper.getDBInstance(AddMyIncomeActivity.this);
                SQLiteDatabase db = helper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put(Constant.DATABASE_INCOME_TABLE_FIELD_HOW_MUCH, Float.parseFloat(howMuch.getText().toString()));
                values.put(Constant.DATABASE_INCOME_TABLE_FIELD_MAIN_SOURCE, commonType.getParentName());
                values.put(Constant.DATABASE_INCOME_TABLE_FIELD_SUB_SOURCE, commonType.getName());
                values.put(Constant.DATABASE_INCOME_TABLE_FIELD_DATE, dateText.getText().toString());
                db.insert(Constant.DATABASE_INCOME_TABLE_NAME, null, values);
                dialog.dismiss();
                Toast.makeText(AddMyIncomeActivity.this, "新增收入成功！", Toast.LENGTH_LONG).show();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dialog.dismiss();
            }
        });
        dataImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePicker(dateText.getText().toString());
            }
        });
    }


    private void showDatePicker(String dateStr) {
        final Date date = DateUtil.fmtStr2Date(dateStr, "yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        DatePickerDialog dpd = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                dateText.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)
        );
        dpd.show();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            //菜单栏返回键功能
            case android.R.id.home:
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}
